package com.design.twords.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.design.twords.MainActivity;
import com.design.twords.R;
import com.design.twords.config.ConstantValue;
import com.design.twords.controller.TimeController;
import com.design.twords.database.BookList;
import com.design.twords.database.OcrWordsList;
import com.design.twords.database.Translation_all;
import com.design.twords.database.Word_all;
import com.design.twords.entity.JsonYdBasic;
import com.design.twords.entity.JsonYdWordDetail;
import com.design.twords.utils.CallBackListener;
import com.design.twords.utils.FanyiV3Yd;
import com.design.twords.utils.MyApplication;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Create by Alen
 * Time:  16:13
 */
public class OcrActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "OcrActivity";

    private EditText ocr_words;
    private Button bt_start, bt_save;
    private ImageView bt_back;
    private ImageView ocr_home,ocr_file;

    private  ProgressDialog progressDialog;

    public ArrayList<String> words = new ArrayList<>();

    private String[] choice = new String[]{"开始听写","开始背单词"};

    //不是单词代码
    private static final int WRONG = 1;
    //get 获取失败
    private static final int GET_FAIL = 2;
    //完成标志
    private static final int FINISH = 3;
    private static final int ON_SAVE = 4;
    private static final int ON_PLAY = 5;


    //暂存标志
    private boolean flag;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case WRONG:
                    Bundle bundle = msg.getData();
                    String errword = bundle.getString("word");
                    Toast.makeText(OcrActivity.this,errword + "不是单词", Toast.LENGTH_LONG).show();
                    break;
                case GET_FAIL:
                    Toast.makeText(OcrActivity.this,"出了一点小问题,请稍后再试", Toast.LENGTH_LONG).show();
                    break;
                case FINISH:
                    showProgressDialog("一个共获取"+words.size()+"个单词");
                    progressDialog.dismiss();
                    break;
                case ON_SAVE:
                    showProgressDialog("正在保存");
                    break;
                case ON_PLAY:
                    showProgressDialog("正在获取数据");
                    break;
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ocr);
        MyApplication.getInstance().addActivity(this);
        initView();
        initListener();

        //将识别出来的单词写入到文本框内
        String str = getIntent().getStringExtra("analysis");
        String[] strs = str.split("##");
        for(int i = 0; i < strs.length; i++){
            ocr_words.append(strs[i]);
            if (i!=strs.length-1)
                ocr_words.append("\n\n");
        }

        //更新用户配置
        //ConfigData.setLastOcrStartTime(TimeController.getCurrentTimeStamp());
        //将ocr 写入到booklist
        List<BookList> bookLists = LitePal.where("bookId = ?", ConstantValue.OCR + "").find(BookList.class);
        if (bookLists.size() <= 0){
            BookList bookList = new BookList();
            bookList.setBookId(ConstantValue.OCR);
            bookList.setBookname(ConstantValue.bookNameById(ConstantValue.OCR));
            bookList.setCreatetime(TimeController.getStringDateDetailNoS(TimeController.getCurrentTimeStamp()));
            bookList.save();
        }



    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.bt_ocr_start:
                flag = false;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.what = ON_PLAY;
                        handler.sendMessage(msg);

                        searchWord(ocr_words.getText().toString());
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }finally {
                            intent.setClass(OcrActivity.this,WordPlayActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putStringArrayList("words",words);
                            intent.putExtra("bundle",bundle);
                            startActivity(intent);
                            progressDialog.dismiss();
                            finish();
                        }
                    }
                }).start();


                break;
            case R.id.bt_ocr_save:
                flag = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.what = ON_SAVE;
                        handler.sendMessage(msg);

                        searchWord(ocr_words.getText().toString());
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        intent.setClass(OcrActivity.this, WordListActivity.class);
                        intent.putExtra("floder_id", ConstantValue.OCR);
                        intent.putExtra("sources", "ocr");
                        startActivity(intent);
                        progressDialog.dismiss();
                        finish();
                    }
                }).start();

                break;
            case R.id.bt_ocr_back:
                onBackPressed();
                break;
            case R.id.orc_home:
                intent.setClass(OcrActivity.this, MainActivity.class);
                startActivity(intent);
                break;
            case R.id.ocr_file:
                intent.setClass(OcrActivity.this, WordListActivity.class);
                intent.putExtra("floder_id", ConstantValue.OCR);
                intent.putExtra("sources", "ocr");
                startActivity(intent);
                break;

        }

    }
    private void showProgressDialog(String content) {
        progressDialog = new ProgressDialog(OcrActivity.this);
        progressDialog.setTitle("请稍后");
        progressDialog.setMessage(content);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    private void searchWord(String text) {
        words.clear();
        String[] wordtext = text.split("\\n");
        for (String wc : wordtext){
            Log.d(TAG,"word: " + wc);
            if (wc == null || wc.equals(""))
                continue;
            //首先查找词库中是否含有该单词
            List<Word_all> word_alls = LitePal.where("word = ?", wc).find(Word_all.class);

            //如果有该单词
            // 判断当前模式为暂存还是立刻播放
            // 立刻播放则直接添加该单词到播放列表
            // 暂存则先判断单词表中是否存在该单词，有则跳过，没有则添加到每日单词表
            if(word_alls.size() > 0){
                if(flag){
                    if (LitePal.where("word = ?",wc).find(OcrWordsList.class).isEmpty()){
                        Log.d(TAG,"today listen: " + wc + "+");
                        OcrWordsList wordsList = new OcrWordsList();
                        wordsList.setWordId(word_alls.get(0).getWordId());
                        wordsList.setWord(wc);
                        wordsList.setWordBook(word_alls.get(0).getWordBook());
                        wordsList.save();
                        while(! wordsList.isSaved()){
                        }

                    }
                }else{
                    words.add(wc);
                }
                continue;
            }else{
                // 当前词库中不存在该单词 则需要向 有道词库发出请求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //没有找到就向有道发送请求获取
                        FanyiV3Yd.requestForYoudao(wc, new CallBackListener() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Message msg = new Message();
                                msg.what = GET_FAIL;
                                handler.sendMessage(msg);
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                //JsonForOcr.analyseJson(response.body().string());
                                try{
                                    analyseJson(response.body().string());
                                }catch (Exception e){
                                    Bundle bundle = new Bundle();
                                    bundle.putString("word", wc);
                                    Message msg = new Message();
                                    msg.what = WRONG;
                                    msg.setData(bundle);
                                    handler.sendMessage(msg);
                                }

                            }
                        });
                    }
                }).start();
            }

        }
        Message msg = new Message();
        msg.what = FINISH;
        handler.sendMessage(msg);

    }
    //分析有道API 数据并将其保存到数据库中
    public void analyseJson(String json){
        Gson gson = new Gson();

        JsonYdWordDetail ydword = gson.fromJson(json, JsonYdWordDetail.class);
        JsonYdBasic basic = ydword.getBasic();
        // 请求成功 后 判断返回状态 如果是单词和句子 则继续
        // 不是单词 则弹出提示
        if (ydword.isWord() || basic == null) {

            Log.d(TAG,ydword.getQuery());

//            long ocrid = ConfigData.getOCRId();
//            ConfigData.setOCRId(ocrid+1);
            long ocrid = TimeController.getCurrentTimeStamp();
            if(flag){
                //设置单词属性
                OcrWordsList wordsList = new OcrWordsList();
                //设置id
                wordsList.setWordId(ocrid);
                //设置单词
                wordsList.setWord(ydword.getQuery());
                wordsList.setWordBook("ocr");
                wordsList.save();
                while(! wordsList.isSaved()){
                }
            }else{
                words.add(ydword.getQuery());
            }

            //将该单词保存到总的单词列表中
            Word_all word_all = new Word_all();
            word_all.setWordId(ocrid);
            word_all.setWord(ydword.getQuery());
            word_all.setWordBook("ocr");
            word_all.setUsPhone(basic==null? "":basic.getUsphonetic());
            word_all.setUkPhone(basic==null? "":basic.getUkphonetic());
            word_all.save();
            if(basic != null){
                //单词获取翻译json
                List<String> explains = basic.getExplains();
                for (String ex : explains) {
                    StringBuilder strBuilder = new StringBuilder();
                    String[] split = ex.split("；");
                    for (int i = 0; i < split.length; i++) {
                        if (i > 2) break;
                        strBuilder.append(split[i] + "; ");
                    }
                    Translation_all translation_all = new Translation_all();
                    translation_all.setWordId(ocrid);
                    translation_all.setWordBook("ocr");
                    translation_all.setCHSMeaning(strBuilder.toString());
                    translation_all.save();

                }
            }else {
                List<String> translation = ydword.getTranslation();
                Translation_all translation_all = new Translation_all();
                translation_all.setWordId(ocrid);
                translation_all.setWordBook("ocr");
                translation_all.setCHSMeaning(translation.get(0));
                translation_all.save();
            }

        }else {
            Bundle bundle = new Bundle();
            bundle.putString("word", ydword.getQuery());
            Message msg = new Message();
            msg.what = WRONG;
            msg.setData(bundle);
            handler.sendMessage(msg);

        }

    }


    public void initView(){
        bt_start = findViewById(R.id.bt_ocr_start);
        bt_back = findViewById(R.id.bt_ocr_back);
        bt_save = findViewById(R.id.bt_ocr_save);
        ocr_home = findViewById(R.id.orc_home);
        ocr_file = findViewById(R.id.ocr_file);
        ocr_words = findViewById(R.id.ocr_words);
    }

    public void initListener(){
        bt_save.setOnClickListener(this);
        bt_back.setOnClickListener(this);
        bt_start.setOnClickListener(this);
        ocr_home.setOnClickListener(this);
        ocr_file.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().removeActivity(this);
    }
}
